package com.cocolover2.andbase.utils;

import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 建议使用{@link AndTextUtil}
 */
@Deprecated
public class DataUtil {

    private DataUtil() {
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    /**
     * 判断输入是否符合给定的格式
     * @param pattern 格式
     * @param input   输入的数据
     * @return true 匹配, false 不匹配
     */
    public static boolean patternRegexString(String pattern, String input) {
        Pattern _pattern = Pattern.compile(pattern);
        Matcher matcher = _pattern.matcher(input);
        if (matcher.find()) {
            return true;
        }
        return false;
    }


    /**
     * 数据大小的显示格式
     */
    public static String formatFileSize(long size) {
        DecimalFormat df = new DecimalFormat(".00");// 保留两位小数
        if (size < 1024)
            return size + "B";
        if (size < 1024 * 1024)
            return df.format(size / 1024.0) + "KB";
        if (size < 1024 * 1024 * 1024l)
            return df.format(size / (1024.0 * 1024.0)) + "MB";
        return df.format(size / (1024.0 * 1024.0 * 1024.0)) + "TB";
    }

    /**
     * 获取MD5加密后的字符串
     *
     * @param origString
     * @return
     * @author LIUBO
     */
    public static String getMD5ofStr(String origString) {
        String origMD5 = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] result = md5.digest(origString.getBytes());
            origMD5 = byteArray2HexStr(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return origMD5;
    }

    private static String byteArray2HexStr(byte[] bs) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bs) {
            sb.append(byte2HexStr(b));
        }
        return sb.toString();
    }

    private static String byte2HexStr(byte b) {
        String hexStr = null;
        int n = b;
        if (n < 0) {
            // 若需要自定义加密,请修改这个移位算法即可
            n = b & 0x7F + 128;
        }
        hexStr = Integer.toHexString(n / 16) + Integer.toHexString(n % 16);
        return hexStr.toUpperCase();
    }

}
